import { Popover, PopoverProps } from "antd";
import { useState, useEffect } from "react";
import { CirclePicker, CirclePickerProps } from "react-color";
import "./index.less";

type Props = {
  value?: string;
  onChange?: (value: Props["value"]) => void;
};

export default function ColorSelect(props: Props) {
  const { value, onChange } = props;

  const [color, setColor] = useState(value);

  useEffect(() => {
    setColor(value);
  }, [value]);

  const handleOnChange: CirclePickerProps["onChange"] = (color, e) => {
    setColor(color.hex);
  };

  const handlePopoverOpenChange: PopoverProps["onOpenChange"] = (visiable) => {
    if (!visiable) {
      onChange?.(color);
    }
  };

  return (
    <Popover
      onOpenChange={handlePopoverOpenChange}
      content={<CirclePicker color={color} onChange={handleOnChange} />}
      trigger={["click"]}
    >
      <div className={"bi-color-picker"} style={{ background: color }}></div>
    </Popover>
  );
}
